package com.tiyende.credit.loop.ui.presenter

import com.tiyende.credit.loop.common.CommonPresenter
import com.tiyende.credit.loop.configs.TiyendeApiPath
import com.tiyende.credit.loop.configs.TiyendeApiUrl
import com.tiyende.credit.loop.configs.TiyendeApiUrl.addCommonParams
import com.tiyende.credit.loop.request.IHttpCallback
import com.tiyende.credit.loop.sdk.analyse.util.TiyendeGoogleUtil
import com.tiyende.credit.loop.ui.contract.IViewContract
import com.tiyende.credit.loop.utils.TiyendeDateUtil
import com.tiyende.credit.loop.utils.helper.TiyendeAnalysisHelper
import com.tiyende.credit.loop.utils.helper.TiyendeConfigsHelper
import com.tiyende.credit.loop.utils.helper.TestAnalysisAddEvent
import com.tiyende.credit.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedKey
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/28 11:59
 * @Annotation：登录
 */
class TiyendeLoginPresenter(private val iView: IViewContract.ITiyendeLoginView): CommonPresenter(iView) {

    /**
     * 登录
     */
    fun requestUserLoginAction(){
        //登录之前，需要验证手机号是否在 app配置 accListV2 里存在
        val accItem = checkUserLoginConfigAccount()
        //accListV2 存在该手机号，直接进入登录成功流程
        if (accItem != null){
            TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_IS_CONFIG_ACCOUNT,true)
            onUserLoginSuccess(accItem.optString("accUid"),accItem.optString("accTk"))
            return
        }
        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_IS_CONFIG_ACCOUNT,false)
        val httpUrl = TiyendeApiUrl.getTiyendeHttpUrl()
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path",TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_LOGIN_NO_CODE_PATH)
                put("mobile",iView.getTiyendeLoginMobile())//手机号
                put("code","0000")//验证码
                put("channelCode", TiyendeGoogleUtil.getInstallReferrer())//渠道号
                put("subChannelCode", TiyendeGoogleUtil.getInstallReferrer())//子渠道号
                put("directLoginFlag","YES")//是否直接登录
                put("notBindWalletFlag","YES")//不自动绑卡
                put("loginParam","")//验证码接口返回的参数
            }
        iView.showTiyendeLoading()
        doHttpPostAction(httpUrl, params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    val userId = obj.optString("userId")
                    val userToken = obj.optString("token")
                    val type = obj.optString("type")

                    //是否是渠道用户
                    val isAdSource = obj.optString("isAdSource")
                    TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_IS_ADSOURCE,"YES" == isAdSource)

                    //登录类型 == 注册，需要打点
                    if (type == "REGISTER"){
                        TestAnalysisAddEvent.addRegisterEvent()
                    }
                    onUserLoginSuccess(userId,userToken)
                }
            }

            override fun onRequestError(error: JSONObject) {
                if (error.optString("code") == "9999"){
                    iView.showTiyendeLoginFailure(error)
                }
            }

            override fun onRequestFinish() {
                iView.hiddenTiyendeLoading()
            }
        })
    }

    /**
     * 获取是否是审核账号信息
     */
    private fun checkUserLoginConfigAccount(): JSONObject?{
        //发送验证码之前，需要验证手机号是否在 app配置 accListV2 里存在
        val customize = TiyendeConfigsHelper.queryTiyendeConfigData()
        var accItem: JSONObject? = null
        if (customize != null){
            val accList = customize.optJSONArray("accListV2")
            if (accList != null && accList.length() > 0){
                for (i in 0..<accList.length()){
                    val obj = accList.optJSONObject(i)
                    if (iView.getTiyendeLoginMobile() == obj.optString("accM")){
                        accItem = obj
                        break
                    }
                }
            }
        }
        return accItem
    }

    /**
     * 登录成功
     */
    private fun onUserLoginSuccess(uid: String, token: String){
        iView.hiddenTiyendeLoading()
        //保存手机号码，个人中心使用
        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_MOBILE, iView.getTiyendeLoginMobile())
        //保存用户登录时间
        val loginTime = TiyendeDateUtil.getFormatTime(System.currentTimeMillis(),"dd/MM/yyyy HH:mm:ss")
        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_LOGIN_TIME,loginTime)
        //保存用户登录状态为已登录
        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_LOGIN,true)
        //保存用户id
        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_USERID,uid)
        //保存用户Token
        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_TOKEN,token)
        //初始化analysis lib 赋值 用户id 和 token
        TiyendeAnalysisHelper.initAnalysisLibAtLoginSuccess()
        //进入主页
        iView.showTiyendeLoginMainPage()
    }
}